#!/usr/bin/env powershell
# create a remote 

$json = @{}
$json["private"] = $false

for ($i = 0; $i -lt $args.Count; $i++) {
    $arg = $args[$i]
    if ($arg -eq "--private" -or $arg -eq "-p") {
        $json["private"] = $true
    }
    elseif ($arg -eq "--description" -or $arg -eq "-d" -and ($i -lt ($args.Count - 1))) {
        $json["description"] = $args[$i + 1];
        $i++
    }
    elseif ($arg[0] -ne '-') {
        $Name = $arg
    }
}

while ($Name.EndsWith(".git")) {
    $len = $Name.Length - 4;
    $Name = $Name.Substring(0, $len)
}

if ($Name.Length -lt 2) {
    Write-Host -ForegroundColor Red "Please input valid repository name !"
    exit 1
}
$json["name"] = $Name
$Domain = "gitee.com"
$WebHost = "https://$Domain/"
$cred = Get-Credential -Title "Please input your Token" -UserName "None (Access Token)"
$json["access_token"] = $cred.GetNetworkCredential().Password





try {
    $body=ConvertTo-Json -InputObject $json
    $res = Invoke-WebRequest -Uri "$WebHost/api/v5/user/repos" -ContentType "application/json" -Method Post -Body $body |ConvertFrom-Json
    $pwn = $res.full_name
    Write-Host "create new project '$pwn' default_branch: $($res.default_branch) id: $($res.id)"
    Write-Host "Your can use 'git remote add origin `$Url' track your repository"
    Write-Host "http: $WebHost/$pwn.git"
    Write-Host "ssh:  git@$Domain`:$pwn.git"
}
catch {
    Write-Host -ForegroundColor Red "create project failed: $_"
}

#Write-Host $result.private_token